<script setup>
import {useRoute, useRouter} from "vue-router";
import {ArrowLeft, ArrowRight, InfoFilled} from "@element-plus/icons-vue";
import ListApis from '@/apis/list.js'
import PackageRemark from "@/views/buyCenter/package/components/PackageRemark.vue";
import SkuDetail from "@/views/buyCenter/package/components/SkuDetail.vue";
import ProductApis from '@/apis/product.js'
import {ElMessage} from "element-plus";
import useCookieStorage from '@/stores/cookieStorage.js'
import {AES_CBC_ENCRYPT, encrypt,encryptAES} from "@/utils/jsencrypt.js";
import config from "@/config/index.js";


const componentsArray=ref([PackageRemark,SkuDetail])
const activeComponentIndex = ref(0)
const route = useRoute()
const router = useRouter()
// route.query.packageId
const breadcrumbArr = ref([])
const draw = ref(false)
const myCookieStorage = useCookieStorage()

// 请求获取的sku原始数据
const skusData = ref([])

const tagNameList = route.query.tagNameList
// 要查看的sku对应的产品列表
const productList = ref([])
const selectedSkuItem = ref(null)

const selectedSkus = computed(() => {
  let arr = []
  for (let i in skusData.value) {
    if (skusData.value[i].checked) {
      arr.push(skusData.value[i])
    }
  }
  return arr;
})
const computedPrice = computed({
  get: () => {
    let sum = 0;
    if (selectedSkus.value.length) {
      for (let i in selectedSkus.value) {
        if (selectedSkus.value[i]) {
          sum += skusData.value[i].discountPrice
        }
      }
    }
    return sum / 100
  },
})


function getSkuList() {
  ListApis.skuList({
    params: {
      packageId: route.query.packageId
    }
  }).then(res => {
    res.data.forEach(e => {
      e.checked = false
    });
    skusData.value = res.data || []
  })
}

function changeCheckTag(checked, index) {
  skusData.value[index].checked = checked
}

function seeRemark() {

  activeComponentIndex.value = 0
  draw.value = true
}

function seeSku(item) {
  selectedSkuItem.value = item
//   获取产品信息,产品名及包含的栏目
  ProductApis.listByProductIds(item.productIds).then(res => {
    res.data.forEach(e=>{
      e.columnModels=[]
    })
    //   产品名称
    productList.value = res.data
    draw.value = true
    activeComponentIndex.value = 1
    productList.value.forEach(e=>{
      ListApis.listByColumnIds({
        params:{
          ids:e.columnIds
        }
      }).then(res1=>{
        e.columnModels=res1.data
      })
    })
  })
}

function init() {
  breadcrumbArr.value.push(route.query.industryName)
  breadcrumbArr.value.push(route.query.examName)
  getSkuList()
  if(route.query.recommendId){
    myCookieStorage.setRecommendId(route.query.recommendId)
    myCookieStorage.setRecommendTime(Date.now())
  }
}

function buy() {
    // selectedSkus
  if(!selectedSkus.value.length){
    ElMessage({
      message: '请选择要购买的科目',
      type: 'warning'
    })
    return;
  }
  // console.log(selectedSkus.value)
  // return;
    router.push({
      path: '/buyCenter/order/pay',
      query: {
        ids: selectedSkus.value.map(e => e.id),
        p: computedPrice.value,
        ...route.query
      }
    })
}
// 生成风向链接到剪贴板
function generate(){
  // console.log("route")
  // 生成二维码并赋值到剪贴板
  if(!myCookieStorage.isLogin) return ElMessage.error('您需要登录');
  router.replace({
    query:{
      ...route.query,
      recommendId:encryptAES(myCookieStorage.userId,config.aes_key)
    }
  }).then(res=>{
    navigator.clipboard.writeText(location.origin+route.fullPath).then(() => {
      ElMessage.success('链接已复制到剪贴板');
    }).catch(err => {
      ElMessage.error('复制失败');
    });
  })
  // console.log(AES_CBC_ENCRYPT(myCookieStorage.userId,config.aes_key))
  // console.log((encryptAES(myCookieStorage.userId)))
}

// console.log(encryptAES(myCookieStorage.userId,config.aes_key))

init()


</script>

<template>
  <div class="package-container">
    <div class="center-content">
      <div class="center-box">
        <div class="header">
          <el-button type="primary" text :icon="ArrowLeft" @click="router.go(-1)">返回</el-button>
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="(item,index) in breadcrumbArr" :key="index">{{ item }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>

        <div class="package-name-container">
          <h1 class="package-name"><span class="package-name-text">{{ route.query.name }}</span>
            <el-icon v-if="route.query.remark" size="16" @click="seeRemark">
              <InfoFilled/>
            </el-icon>
          </h1>
          <h2>有效期:<span>{{ route.query.days }}</span>天</h2>
        </div>
        <div v-if="route.query.cover" class="package-cover">
          <img :src="route.query.cover">
        </div>

        <div class="the-content">
          <div class="tags margin-top-20">
            <div>标签:</div>
            <div class="the-tags">
              <el-tag round class="my-tag" type="success" v-for="(i, index) in tagNameList" :key="index">{{
                  i
                }}
              </el-tag>
            </div>
          </div>
          <div class="selected margin-top-20" style="min-height: 70px;">
            <div class="title">已选科目:</div>
            <div class="selected-tags">
              <el-tag effect="plain" class="my-tag" round v-for="(item, index) in selectedSkus" :key="index">
                {{
                  item.name
                }}
              </el-tag>
            </div>

          </div>
          <div class="kus margin-top-20">
            <div class="title">添加科目:</div>
            <div class="check-tags">
              <el-check-tag class="my-tag" round :checked="item.checked"
                            @change="(val) => changeCheckTag(val, index)" v-for="(item, index) in skusData" :key="index"
                            style="margin-right: 8px"><span>
                {{ item.name }}
                <el-icon size="12" @click="seeSku(item)">
                   <InfoFilled/>
                </el-icon>
              </span>
              </el-check-tag>
            </div>


          </div>
        </div>
        <div class="footer">
          <div class="dialog-footer">
            <div class="left">
                    <span class="black">
                        合计：
                    </span>
              <span class="unit">￥</span>
              <span class="money">
                        {{ computedPrice.toFixed(2) }}
                    </span>

            </div>
            <div class="right">
              <el-button type="primary" @click="buy">购买</el-button>
            </div>
          </div>
        </div>
      </div>

    </div>
    <el-drawer v-model="draw" direction="rtl" size="40%">
      <component :is="componentsArray[activeComponentIndex]" :productList="productList" :selectedSkuItem="selectedSkuItem" @generate="generate"></component>
    </el-drawer>
  </div>
</template>

<style scoped>
.package-container {

  background: url('@/assets/images/app_background.png');
  background-size: cover;
}

.center-content {
  width: 1400px;
  margin: 0 auto;
  padding: 32px;
  box-sizing: border-box;
}

.center-box {
  background: white;
  padding: 16px;
}

.center-box .header {
  display: flex;
  gap: 32px;
  align-items: center;
  border-radius: 12px;
}

.package-name-container h2 {
  text-align: center;
  margin-left: 180px;
}

.package-name-container h2 span {
  color: red;
}

.package-name {
  text-align: center;
  font-weight: bolder;
}

.package-cover {
  text-align: center;

}

.package-cover img {
  height: 250px;
}

.package-name-text {
  color: transparent;
  background-image: linear-gradient(180deg, #FFA500 35%, #FFD700 50%, #FFA500 65%);
  background-clip: text;
  animation: blink 2.5s infinite linear;
  font-weight: bold;
  text-shadow: 0 0 4px #FFD700;
}

@keyframes blink {
  0% {
    background-position: 0 0;
    text-shadow: 0 0 4px #FFA500;
  }
  50% {
    text-shadow: 0 0 4px #FFD700;
  }
  100% {
    background-position: 0px 100px;
    text-shadow: 0 0 4px #FFA500;
  }
}

.the-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.margin-top-20.tags {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.margin-top-20 .the-tags {
  display: flex;
  align-items: center;
  gap: 10px;
}

.selected-tags {
  display: flex;
  align-items: center;
  align-content: flex-start;
  gap: 10px;
  flex-wrap: wrap;
}

.selected.margin-top-20 {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.margin-top-20.kus {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.kus .check-tags {
  display: flex;
  align-content: flex-start;
  align-items: flex-start;
  gap: 10px;
  flex-wrap: wrap;
}

.footer {
  padding: 16px 0;
}

.footer .dialog-footer {
  font-weight: bold;
  font-size: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer .unit {
  color: red;
  font-size: 16px;
}

.dialog-footer .money {
  font-weight: bolder;
  color: red;
}
</style>